
local jass = require 'jass.common'
local japi = require 'jass.japi'
local md5 = japi['md5']

--同步数据
local mt = {}

local mark_list = {}
local end_sync = {}
local sync_data = {}


local function sync_hash(player,message)
    local pid = jass.GetPlayerId(player)
    local idx = string.find(message,'==')
    local group = {}

    if not idx then
        print('伪造同步')
        return
    end
    local class = string.sub(message,1,idx-1)
    local hash = string.sub(message,idx+2,#message)

    --同步完成的数据不允许再次同步
    if end_sync[class] then
        return
    end

    if not mark_list[class] then
        mark_list[class] = {}
    end
    mark_list[class][pid] = hash


    --在线玩家
    for a=1,12 do
        local handle = jass.Player(a-1)
        local id = jass.GetPlayerId(handle)
        if jass.GetPlayerController(handle) == jass.MAP_CONTROL_USER and jass.GetPlayerSlotState(handle) == jass.PLAYER_SLOT_STATE_PLAYING then
            table.insert(group,handle)
            --有玩家没完成同步
            if not mark_list[class][id] then
                return
            end
        end
    end

    --校验哈希数据
    for _,handle in ipairs(group) do
        local id = jass.GetPlayerId(handle)
        if mark_list[class][id]~=hash then
            print('====校验异常====')
            return
        end
    end

    --完成标签
    end_sync[class] = true

    mt.finish_sync(class,sync_data[class])
end



local trg = jass.CreateTrigger()
japi.DzTriggerRegisterSyncData(trg,'同步服务器数据',false)
jass.TriggerAddAction(trg,function ()
    local message = japi.DzGetTriggerSyncData()
    local player = japi.DzGetTriggerSyncPlayer()
    sync_hash(player,message)
end)

--发送同步消息
function mt.send_sync(class,result)
    if not result then
        return
    end
    local hash = md5(result)
    local post = ('%s==%s'):format(class,hash)
    sync_data[class] = result
    japi.DzSyncData('同步服务器数据', post)
end

--同步完成
function mt.finish_sync(class,result)

end


return mt